package jobase

import (
	"fmt"
	"gitee.com/jolib/jokode"
	"strings"
	"time"
)

var ZeroTime time.Time

func DateToA(t time.Time) string {
	if t.IsZero() {
		return ""
	} else {
		return t.Format(jokode.DefDateFormat)
	}
}

func TimeToA(t time.Time) string {
	if t.IsZero() {
		return ""
	} else {
		return t.Format(jokode.DefTimeFormat)
	}
}

func TimeMsToA(t time.Time) string {
	if t.IsZero() {
		return ""
	} else {
		return t.Format(jokode.DefTimeFormatMs)
	}
}

func AToTime(t string) time.Time {
	t = strings.TrimSpace(t)

	if t == "" {
		return ZeroTime
	}

	dt := ""
	ti := "00:00:00"

	if idx := strings.IndexByte(t, ' '); idx > 0 {
		dt = t[:idx]
		ti = t[idx+1:]
	} else {
		dt = t
	}

	ymd := strings.Split(dt, "-")
	if len(ymd) != 3 {
		return ZeroTime
	}

	y := ymd[0]
	M := ymd[1]
	d := ymd[2]

	if len(M) < 2 {
		M = "0" + M
	}

	if len(d) < 2 {
		d = "0" + d
	}

	ti = strings.TrimSpace(ti)

	hms := strings.Split(ti, ":")

	h := ""
	m := ""
	s := ""
	x := ""

	hmsLen := len(hms)
	if hmsLen < 2 {
		return ZeroTime
	} else if hmsLen == 2 {
		h = hms[0]
		m = hms[1]
		s = "00"
		x = "000"
	} else {
		h = hms[0]
		m = hms[1]

		if idx := strings.IndexByte(hms[2], '.'); idx > 0 {
			s = hms[2][:idx]
			x = hms[2][idx+1:]
		} else {
			s = hms[2]
			x = "000"
		}
	}

	if len(h) < 2 {
		h = "0" + h
	}

	if len(m) < 2 {
		m = "0" + m
	}

	if len(s) < 2 {
		s = "0" + s
	}

	switch len(x) {
	case 0:
		x = "000"
	case 1:
		x = "00" + x
	case 2:
		x = "0" + x
	default:
		x = x[:3]
	}

	full := fmt.Sprintf("%s-%s-%s %s:%s:%s.%s", y, M, d, h, m, s, x)
	if p, err := time.ParseInLocation(jokode.DefTimeFormatMs, full, time.Local); err != nil {
		jokode.Errorf("try parse date string '%s' fail, error info: %v", full, err)
		return ZeroTime
	} else {
		return p
	}
}
